package com.yueya.auth.filter;

import com.yueya.auth.config.AuthProperties;
import com.yueya.auth.utils.JwtUtil;
import com.yueya.auth.utils.RequestUtil;
import com.yueya.common.util.JsonMapper;
import com.yueya.common.web.RestResult;
import io.jsonwebtoken.JwtException;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import static com.yueya.auth.config.AuthConstant.TOKEN_NAME;

public class PmsUserFilter extends UserFilter {

    private AuthProperties authProperties;
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse= (HttpServletResponse) response;
        if (authProperties.isJwtMode()) {
            RequestUtil.setHeader((HttpServletRequest) request,(HttpServletResponse) response);
        }
        httpServletResponse.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
        return false;
    }
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        if (authProperties.isJwtMode()){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
                RequestUtil.setHeader(httpRequest,httpResponse);
                return false;
            }
        }
        return super.preHandle(request,response);
    }

    public void setAuthProperties(AuthProperties authProperties) {
        this.authProperties = authProperties;
    }
}
